package com.example.xunua_today_in_history;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xunua_today_in_history.Adapter.HistoryAdapter;
import com.example.xunua_today_in_history.bean.HistoryBean;
import com.example.xunua_today_in_history.bean.LaohuangliBean;
import com.example.xunua_today_in_history.utils.ContentURL;
import com.example.xunua_today_in_history.utils.OkHttpUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private ListView lv;
    private TextView tv_yinli,tv_day,tv_week,tv_yangli,tv_baiji,tv_wuxing,tv_chongsha,tv_jishen,tv_xiongshen,
    tv_yi,tv_ji;//headerView中的组件
    private ImageButton imgbtn;
    private ArrayList<HistoryBean.ResultBean> mdata;
    private HistoryBean historyBean;
    private HistoryAdapter adapter;
    private OkHttpUtil util=new OkHttpUtil();

    //改日历的
    private Calendar calendar;  //用于获取系统时间
    private Date date ;
    private int month,day,year;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    adapter.notifyDataSetChanged();
                    break;
                case 1:
                    Toast.makeText(MainActivity.this, ""+msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    Toast.makeText(MainActivity.this, "接口今日使用上限了，请隔日再试", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        //不知道哪里的问题 第一次加载黄历  和历史上的今天会出现不显示的情况，所以把获取数据的操作放在最后加载一次。
        String time=year+"-"+(month+1)+"-"+day;
        String laohuangliURL = ContentURL.getLaohuangliURL(time);
        getLaoHuangLi(laohuangliURL);

        //更新历史上的今天
        String todayHistoryURL = ContentURL.getTodayHistoryURL("1.0", (month + 1), day);
        getLishishangjintian(todayHistoryURL);
    }

    private void initView() {
        lv=findViewById(R.id.main_lv);
        imgbtn=findViewById(R.id.main_imgbtn);
        imgbtn.setOnClickListener(this);
        date=new Date();//获取时间
        mdata=new ArrayList<>();
        addHeadAndFootView();
        //加载数据 历史上的今天
        calendar=Calendar.getInstance();//Calendar 采用的是单例模式，通过：Calendar.getInstance();获取他的实例。使用Calendar.setTime(Date date);设置时间 。
        calendar.setTime(date); //把时间给calendar
        month=calendar.get(Calendar.MONTH);  //通过calendar来拿
        day=calendar.get(Calendar.DAY_OF_MONTH);
        year=calendar.get(Calendar.YEAR);
        final String url=ContentURL.getTodayHistoryURL("1.0",(month+1),day);

        //设置适配器
        adapter=new HistoryAdapter(mdata,this);
        lv.setAdapter(adapter);
//        getLishishangjintian(url);
        //为ListView设置点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {  //避免点击头部view而软件崩溃
                    return;
                }
                Intent intent = new Intent(MainActivity.this, HistoryDescActivity.class);
                HistoryBean.ResultBean resultBean = mdata.get(position-1);//因为有一个头部标记，所以点击item第五条新闻的索引为5，而mDate是从0开始，size=4。因此索引position减去1。
                String his_id = resultBean.get_id();
                intent.putExtra("hisId",his_id);
                startActivity(intent);
            }
        });
    }

    private void getLishishangjintian(final String url) {
        //okhttp3异步获取
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s = util.connect_get(url);
                    mdata.clear();
                    historyBean=new Gson().fromJson(s,HistoryBean.class);
                    List<HistoryBean.ResultBean> list=historyBean.getResult();
                    Collections.reverse(list);
                    for (int i = 0; i < 5; i++) {//主页最多显示五条数据
                        mdata.add(list.get(i));
                    }
                    handler.sendEmptyMessage(0);
                }catch (Exception e){
                    handler.sendEmptyMessage(-1);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 添加头部 和 底部 view
     */
    private void addHeadAndFootView() {
        View headerView = LayoutInflater.from(this).inflate(R.layout.headerview, null);
        initHeaderView(headerView);
        //加载数据到HeaderView
        lv.addHeaderView(headerView);
        View footerView = LayoutInflater.from(this).inflate(R.layout.footerview, null);
        footerView.setTag("footer");
        lv.addFooterView(footerView);
        footerView.setOnClickListener(this);
    }

    private void initHeaderView(View view) {
        //初始化组件
        tv_yinli=view.findViewById(R.id.main_header_tv_nongli);
        tv_day=view.findViewById(R.id.main_header_tv_day);
        tv_week=view.findViewById(R.id.main_header_tv_week);
        tv_yangli=view.findViewById(R.id.main_header_tv_yangli);
        tv_baiji=view.findViewById(R.id.main_header_tv_baiji);
        tv_wuxing=view.findViewById(R.id.main_header_tv_wuxing);
        tv_chongsha=view.findViewById(R.id.main_header_tv_chongsha);
        tv_jishen=view.findViewById(R.id.main_header_tv_jishen);
        tv_xiongshen=view.findViewById(R.id.main_header_tv_xiongshen);
        tv_yi=view.findViewById(R.id.main_header_tv_yi);
        tv_ji=view.findViewById(R.id.main_header_tv_ji);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String time=sdf.format(date);
        String url= ContentURL.getLaohuangliURL(time);
//        getLaoHuangLi(url);
    }

    private void getLaoHuangLi(final String url) {
        //加载网络  老黄历

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s = util.connect_get(url);
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.getString("error_code").equals("10012")){
                        String reason = jsonObject.getString("reason");
                        Message message = new Message();
                        message.what=1;
                        message.obj=reason;
                        handler.sendMessage(message);
                    }
                    LaohuangliBean bean=new Gson().fromJson(s,LaohuangliBean.class);
                    LaohuangliBean.ResultBean result = bean.getResult();
                    //因为数据源得到的不符合要求，是yyyy-MM-dd格式, 没有星期，所以通过函数计算星期
                    String[] yanglisplit = result.getYangli().split("-");
                    String week = getWeek(Integer.parseInt(yanglisplit[0]), Integer.parseInt(yanglisplit[1]), Integer.parseInt(yanglisplit[2]));
                    tv_week.setText(week);
                    tv_yangli.setText("公历 "+yanglisplit[0]+"年"+yanglisplit[1]+"月"+yanglisplit[2]+"日 "+week+" (阳历)");
                    tv_day.setText(yanglisplit[2]);
                    tv_yinli.setText("农历"+result.getYinli()+"(阴历)");
                    tv_baiji.setText("彭祖百忌:"+result.getBaiji());
                    tv_wuxing.setText("五行:"+result.getWuxing());
                    tv_chongsha.setText("冲煞:"+result.getChongsha());
                    tv_jishen.setText("吉神宜趋:"+result.getJishen());
                    tv_xiongshen.setText("凶神宜忌:"+result.getXiongshen());
                    tv_yi.setText("宜 : "+result.getYi());
                    tv_ji.setText("忌 : "+result.getJi());
                /**
                 * {"reason":"successed","result":{"id":"3549","yangli":"2019-12-06","
                 * yinli":"己亥(猪)年十一月十一","wuxing":"涧下水 满执位",
                 * "chongsha":"冲羊(辛未)煞东","baiji":"丁不剃头头必生疮 丑不冠带主不还乡",
                 * "jishen":"守日 天巫 福德 玉宇 玉堂","yi":"诸事不宜",
                 * "xiongshen":"月厌 地火 九空 大煞 归忌","ji":"诸事不宜"},
                 * "error_code":0}
                 */
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取你设置的Calendar那年那月那日是星期几，必须要减一，
     * 因为数组下标从0开始，而她返回的是数组的内容，
     * 是数组{1,2,3,4,5,6,7}中用1~7来表示：星期天，星期一，星期二，星期三，星期四，星期五，星期六 。
     * 如果当天是星期一她会返回2，所以减一，才等于1，才是你想要的，如果是星期天就返回1-1=0咯！
     * @param year
     * @param month
     * @param day
     * @return
     */
    private String getWeek(int year, int month, int day) {
        Calendar calendar=Calendar.getInstance();
        calendar.set(year,month-1,day);
        String [] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        int index=calendar.get(Calendar.DAY_OF_WEEK)-1;
//        if (index<0){
//            index=0;
//        }
        return weeks[index];
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.main_imgbtn){
            MonthDialog();
        } else if (v.getTag().equals("footer")){
            Intent intent = new Intent(this, HistoryActivity.class);
            if (historyBean!=null) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("history",historyBean);
                intent.putExtras(bundle);
            }
            startActivity(intent);
        }
    }

    /**
     * Style
     * int THEME_TRADITIONAL = 1;
     * int THEME_HOLO_DARK = 2;
     * int THEME_HOLO_LIGHT = 3;
     * int THEME_DEVICE_DEFAULT_DARK = 4;
     * int THEME_DEVICE_DEFAULT_LIGHT = 5;   分别对应五种风格
     */
    //日期选择对话框
    private void MonthDialog(){
        Calendar calendar=Calendar.getInstance();
        DatePickerDialog dialog=new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                //更新老黄历的显示
                String time=year+"-"+(month+1)+"-"+dayOfMonth;
                String laohuangliURL = ContentURL.getLaohuangliURL(time);
                getLaoHuangLi(laohuangliURL);

                //更新历史上的今天
                String todayHistoryURL = ContentURL.getTodayHistoryURL("1.0", (month + 1), dayOfMonth);
                getLishishangjintian(todayHistoryURL);
            }
        },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));//最初选定的年份
        dialog.show();
    }


    long time=0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            if (System.currentTimeMillis() - time > 2000) {
                Toast.makeText(getApplicationContext(), "再次点击退出程序!", Toast.LENGTH_SHORT).show();
                time=System.currentTimeMillis();
            }else {
                System.exit(0);
            }
        }
        return true;
    }
}
